<template>
  <div class="scree-plot-chart">
    <div class="chart-title">
      <span class="title-text">{{ title }}</span>
      <!-- ✅ 单独导出按钮 -->
      <button
        v-if="showExportButton"
        size="mini"
        class="export-btn"
        @click="downloadImage"
        :title="`导出 ${title} 为 PNG`"
      >
        导出图片
      </button>
    </div>
    <div ref="chartContainer" class="chart-container"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "ScreePlotChart",
  props: {
    title: { type: String, default: "碎石图 (Scree Plot)" },
    screeX: { type: Array, required: true, default: () => [] },
    screeBar: { type: Array, required: true, default: () => [] },
    screePlot: { type: Array, required: true, default: () => [] },
    width: { type: String, default: "100%" },
    height: { type: String, default: "400px" },
    showExportButton: { type: Boolean, default: true }, // ✅ 控制导出按钮
    exportFileName: { type: String, default: "" }, // ✅ 文件名前缀
  },
  data() {
    return { chart: null };
  },
  mounted() {
    this.initChart();
    window.addEventListener("resize", this.handleResize);
  },
  beforeDestroy() {
    if (this.chart) this.chart.dispose();
    window.removeEventListener("resize", this.handleResize);
  },
  watch: {
    screeX: { handler() { this.updateChart(); }, deep: true },
    screeBar: { handler() { this.updateChart(); }, deep: true },
    screePlot: { handler() { this.updateChart(); }, deep: true },
  },
  methods: {
    initChart() {
      if (!this.$refs.chartContainer) return;
      this.chart = echarts.init(this.$refs.chartContainer);
      this.updateChart();
    },
    updateChart() {
      if (!this.chart) return;
      const option = {
        backgroundColor: "#fff",
        grid: { left: "10%", right: "8%", bottom: "15%", top: "15%", containLabel: true },
        xAxis: {
          type: "category",
          name: "主成分数",
          nameLocation: "middle",
          nameGap: 30,
          nameTextStyle: { fontSize: 14, fontWeight: "bold" },
          data: this.screeX,
          axisLine: { show: true, lineStyle: { color: "#333", width: 2 } },
          axisTick: { show: true, length: 6 },
          axisLabel: { fontSize: 12, color: "#333" },
        },
        yAxis: [
          {
            type: "value",
            name: "贡献率",
            nameLocation: "middle",
            nameGap: 50,
            nameTextStyle: { fontSize: 14, fontWeight: "bold" },
            min: 0,
            max: 1,
            axisLine: { show: true, lineStyle: { color: "#333", width: 2 } },
            axisTick: { show: true, length: 6 },
            axisLabel: { fontSize: 12, color: "#333" },
            splitLine: { show: true, lineStyle: { color: "#e0e0e0", type: "solid" } },
          },
        ],
        series: [
          {
            name: "Individual Variance",
            type: "bar",
            data: this.screeBar,
            itemStyle: { color: "#4A90E2", borderColor: "#4A90E2", borderWidth: 1 },
            emphasis: { itemStyle: { color: "#2E5BBA", borderColor: "#2E5BBA" } },
            barWidth: "60%",
          },
          {
            name: "Cumulative Variance",
            type: "line",
            data: this.screePlot,
            lineStyle: { color: "#FF4444", width: 3 },
            itemStyle: { color: "#FF4444", borderColor: "#FF4444", borderWidth: 2 },
            symbol: "circle",
            symbolSize: 8,
          },
          {
            name: "95% Reference",
            type: "line",
            data: this.screeX.map(() => 0.95),
            lineStyle: { color: "#00AA00", width: 2, type: "dashed" },
            symbol: "none",
            tooltip: { show: false },
          },
        ],
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "cross", crossStyle: { color: "#999" } },
          formatter: function (params) {
            let result = `<div style="padding: 8px;"><div><strong>PC ${params[0].axisValue}</strong></div>`;
            params.forEach((param) => {
              if (param.seriesName === "Individual Variance") {
                result += `<div>Individual: ${(param.value * 100).toFixed(1)}%</div>`;
              } else if (param.seriesName === "Cumulative Variance") {
                result += `<div>Cumulative: ${(param.value * 100).toFixed(1)}%</div>`;
              }
            });
            result += `</div>`;
            return result;
          },
          backgroundColor: "rgba(0,0,0,0.8)",
          borderColor: "#4A90E2",
          borderWidth: 1,
          textStyle: { color: "#fff", fontSize: 12 },
        },
      };
      this.chart.setOption(option, true);
    },
    handleResize() {
      if (this.chart) this.chart.resize();
    },

    /** ✅ 提供给父组件：获取 base64 */
    getChartBase64() {
      if (!this.chart) return null;
      return this.chart.getDataURL({
        type: "png",
        pixelRatio: 2,
        backgroundColor: "#fff",
      });
    },

    /** ✅ 单独导出 PNG */
    downloadImage() {
      const base64 = this.getChartBase64();
      if (!base64) return;

      const ts = new Date();
      const pad = (n) => (n < 10 ? "0" + n : "" + n);
      const stamp = `${ts.getFullYear()}${pad(ts.getMonth() + 1)}${pad(ts.getDate())}-${pad(ts.getHours())}${pad(ts.getMinutes())}${pad(ts.getSeconds())}`;

      const name =
        (this.exportFileName && this.exportFileName.trim()) ||
        (this.title ? this.title.replace(/[\/\\:*?"<>|]/g, "_") : "chart");

      const a = document.createElement("a");
      a.href = base64;
      a.download = `${name}-${stamp}.png`;
      a.click();
    },
  },
};
</script>

<style scoped>
.scree-plot-chart {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chart-title {
  position: relative;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
  padding: 0 10px;
}

.title-text {
  display: inline-block;
  padding: 0 40px; /* 给右边按钮留空间 */
}

.export-btn {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  font-size: 12px;
  padding: 2px 8px;
  background-color: #409eff;
  border: none;
  border-radius: 4px;
  color: #fff;
  cursor: pointer;
}
.export-btn:hover {
  background-color: #66b1ff;
}

.chart-container {
  flex: 1;
  min-height: 300px;
  width: 100%;
}
</style>
